package com.heima.search.service.impl;


import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import com.heima.search.service.IUserSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private IUserSearchService userSearchService;

    @Autowired
    IArticleSearchService articleSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        // 根据关键字查询文章标题
        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());
        // 分页查询
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");
        Page<ApArticleSearch> searchPage = articleRepository.search(query, page);

        // 异步保存搜索记录
       /* User user = AppThreadLocalUtil.get();
        Integer userId = null;
        if (user != null) {
            userId = user.getUserId();
        }
        userSearchService.saveRecord(userId, dto.getEquipmentId(), dto.getSearchWords());*/
        User user = AppThreadLocalUtil.get();

        Integer userId = null;

        if (user != null) {
            userId = user.getUserId();
        }
        userSearchService.saveRecord(userId,dto.getEquipmentId(),dto.getSearchWords());

        return ResponseResult.okResult(searchPage.getContent());
    }
}
